package city.spring.configure.security;

import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义身份验证入口点。
 * 当未登录或者登录过期时，因此无法访问系统的时候，异常信息走这个对象来处理
 *
 * @author HouKunLin
 * @date 2019/12/1 0001 21:57
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationEntryPoint.class);
    private final AuthenticationEntryPoint authenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
    private final String htmlMimeType = ContentType.TEXT_HTML.getMimeType();

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        logger.error("OAuth2 错误 -> 自定义身份验证入口点：{}", e.getMessage());

        /*
        // 为了适配授权码模式，有可能是直接在浏览器打开获取授权码，如果当前用户已经登录则跳转到登陆页面
        String accept = request.getHeader("Accept");
        if (accept != null && accept.toLowerCase().contains(htmlMimeType)) {
            String redirectUri = request.getParameter("redirect_uri");
            if (StringUtils.isNotBlank(redirectUri)) {
                response.sendRedirect(redirectUri);
                return;
            }
        }*/
        authenticationEntryPoint.commence(request, response, e);
        /*
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json; charset=UTF-8");
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("msg", e.getMessage());
        map.put("type", e.getClass().getName());
        map.put("message", "访问此资源需要完全的身份验证");
        response.getWriter().write(objectMapper.writeValueAsString(map));*/
    }

    @PostConstruct
    public void postConstruct() {
        logger.debug("自定义身份验证入口点: {}", this);
    }
}
